# -*- coding: utf-8 -*-

"""
@Datetime: 2018/8/28
@Author: Zhang Yafei
"""
import json
import uuid

import tornado.web
import tornado.ioloop
import tornado.websocket


class IndexHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        self.render('index.html')


class ChatHandler(tornado.websocket.WebSocketHandler):

    users = set()
    messages = []

    def open(self, *args, **kwargs):
        """
        客户端和服务器已经建立连接
        1.连接
        2.握手
        :param args:
        :param kwargs:
        :return:
        """
        ChatHandler.users.add(self)
        uid = str(uuid.uuid4())
        self.write_message(uid)

        for msg in ChatHandler.messages:
            content = self.render_string('message.html', **msg)
            self.write_message(content)

    def on_message(self, message):
        msg = json.loads(message)
        ChatHandler.messages.append(message)

        for client in ChatHandler.users:
            content = self.render_string('message.html',**msg)
            client.write_message(content)

    def on_close(self):
        """
        客户端主动关闭连接
        :return:
        """
        ChatHandler.users.remove(self)


def run():
    settings = {
        'template_path': 'templates',
        'static_path': 'static',
    }
    application = tornado.web.Application([
        (r"/", IndexHandler),
        (r"/chat", ChatHandler),
    ], **settings)
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    run()